package com.qfedu.fmmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.fmmall.config.ObjectMapperUtil;
import com.qfedu.fmmall.entity.*;
import com.qfedu.fmmall.mapper.ProductImgMapper;
import com.qfedu.fmmall.mapper.ProductMapper;
import com.qfedu.fmmall.mapper.ProductParamsMapper;
import com.qfedu.fmmall.mapper.ProductSkuMapper;
import com.qfedu.fmmall.service.ProductService;
import com.qfedu.fmmall.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * <p>
 * 商品 商品信息相关表：分类表，商品图片表，商品规格表，商品参数表 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductImgMapper productImgMapper;
    @Resource
    private ProductSkuMapper productSkuMapper;
    @Resource
    private ProductParamsMapper productParamsMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询推荐商品接口
     *
     * @return
     */
    public ResultVO listRecommendProducts() {
        List<ProductVO> list = new ArrayList<>();
        Page<Product> page = new Page(0, 3);
        LambdaQueryWrapper<Product> qu = new LambdaQueryWrapper<>();
        qu.orderByDesc(Product::getCreateTime);
         productMapper.selectPage(page, qu);
        List<Product> records = page.getRecords();
        records.forEach(item->{
            ProductVO vo=new ProductVO();
            BeanUtils.copyProperties(item, vo);
            List<ProductImg> img = productImgMapper.selectList(new LambdaQueryWrapper<ProductImg>().
                    eq(ProductImg::getItemId, item.getProductId()));
            List<ProductSku> sku = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().
                    eq(ProductSku::getProductId, item.getProductId()));
                     vo.setImgs(img);
                     vo.setSkus(sku);
                     list.add(vo);
        });
        return ResultVO.success(list,"成功！");
    }

    /**
     * 商品信息接口
     * @param id
     * @return
     */
    @Override
    public ResultVO getProduct(String id) {
//         根据商品id查询缓存
        String productInfo = (String) stringRedisTemplate.boundHashOps("product").get(id);
        if (productInfo != null && !("null".equals(productInfo))) {
            HashMap hashMap = null;
            try {
                hashMap = ObjectMapperUtil.getObjectMapper().readValue(productInfo, HashMap.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            return ResultVO.success(hashMap, "200");
        } else {
            LambdaQueryWrapper<Product> q = new LambdaQueryWrapper<>();
            q.eq(Product::getProductId, id);
            q.eq(Product::getProductStatus, 1);
            LambdaQueryWrapper<ProductImg> q1 = new LambdaQueryWrapper<>();
            q1.eq(ProductImg::getItemId, id);
            LambdaQueryWrapper<ProductSku> q2 = new LambdaQueryWrapper<>();
            q2.eq(ProductSku::getProductId, id);
            Product product = productMapper.selectOne(q);
            if (product == null) {
//                缓存数据库都没有，存储一个空串，防止恶意攻击，2过期
                stringRedisTemplate.boundHashOps("product").put("null", "null");
                stringRedisTemplate.expire("product", 2, TimeUnit.MINUTES);
                return ResultVO.error("该商品信息不存在！");
            }
            List<ProductImg> productImgs = productImgMapper.selectList(q1);
            List<ProductSku> productSkus = productSkuMapper.selectList(q2);
            Map<String, Object> map = new HashMap<>();
            map.put("product", product);
            map.put("productImgs", productImgs);
            map.put("productSkus", productSkus);
            try {
//                 把商品数据存储到redis中
                stringRedisTemplate.boundHashOps("product").put(id, ObjectMapperUtil.getObjectMapper().writeValueAsString(map));
                stringRedisTemplate.expire("product", 2, TimeUnit.HOURS);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            return ResultVO.success(map, "200");
        }
    }

    /**
     * 查询商品参数信息
     * @param id
     * @return
     */
    @Override
    public ResultVO productParams(String id) {

        ProductParams productParams = productParamsMapper.productParams(id);
        if (productParams != null) {
            return ResultVO.success(productParams,"200");
        }
        return ResultVO.error("查询不到该商品信息");
    }

}
